package mk.edu.ii.navigatemacedonia;


import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

public class SiteInfoActivity extends Activity {
		private Intent intent;	
		private Site site;
		private Drawable image;
		private String image_url;
		// Initialize a handler on the main thread.
	    private Handler handler = new Handler();
	    
	    ImageView imageView = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.siteinfoview);
        
        intent = getIntent();
        loadSiteInfo();
        
        imageView = (ImageView)findViewById(R.id.third_image_frame);
        imageView.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showImageDialog(v).show();
			}
		});
        ImageButton mapButton = (ImageButton) findViewById(R.id.map_button);
		mapButton.setOnClickListener(new Button.OnClickListener() {
		public void onClick(View v){
			Intent mapView = new Intent(v.getContext(),MapPreviewActivity.class);
			mapView.putExtra("site", site);
			mapView.putExtra("longitude", intent.getDoubleExtra("longitude", 0d));
			mapView.putExtra("latitude", intent.getDoubleExtra("latitude", 0d));
			startActivity(mapView);
		}});


		ImageView rateImageView = (ImageView)findViewById(R.id.rating_imageview);
		rateImageView.setOnClickListener(new Button.OnClickListener(){
			public void onClick(View v){
				showRateDialog(v);
			}
		});
        }
    
    public void loadSiteInfo(){
    	site = (Site)intent.getSerializableExtra("site");
    	
    	TextView siteName = (TextView)findViewById(R.id.third_TextView01_1);
    	TextView siteCategory = (TextView)findViewById(R.id.third_TextView02_1);
    	TextView distance = (TextView)findViewById(R.id.third_TextView03_1);
    	TextView siteInfo = (TextView)findViewById(R.id.third_siteinfo);
    	ImageView ratingBar = (ImageView)findViewById(R.id.rating_imageview);
       
        siteName.setText(site.getSiteName());
        siteCategory.setText(site.getSiteCategory());
        ratingBar.setImageResource(getRatingImageId(site.getSiteRating()));
        distance.setText(site.getSiteDistance()+" "+Site.getBearingString(site.getSiteBearing()));
        image_url=site.getSiteImage();
        
        loadImageThread();
        siteInfo.setText(site.getSiteDescription());
        
        
    }
    
    public void load_image(String image_url)
    {
    	 image = ImageOperations(image_url);
    }
    
    private Drawable ImageOperations(String url) {
    	
		try {			
			InputStream is = (InputStream) this.fetch(ServiceURL.URL+url);
			Drawable d = Drawable.createFromStream(is, "src");						
			return d;
		} catch (MalformedURLException e) {			
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
    		
	}

	public Object fetch(String address) throws MalformedURLException,IOException {
		URL url = new URL(address);
				
		URLConnection connection=url.openConnection();
		connection.setReadTimeout(5000);
				
		Object content = connection.getContent();
		return content;
	}

	
	private void loadImageThread() {
		Thread thread = new Thread(null, doBackgroundThreadProcessing, "Background");
		thread.start();
	}
	
	private Runnable doBackgroundThreadProcessing = new Runnable() {
		public void run() {
			backgroundThreadProcessing();
		}
	};
	
	// Method which does some processing in the background.
	private void backgroundThreadProcessing() {
		load_image(image_url);
		handler.post(doUpdateGUI);
	}
	// Runnable that executes the update GUI method.
	private Runnable doUpdateGUI = new Runnable() {
		public void run() {
			updateGUI();
		}
	};
	private void updateGUI() {
		
    	if(image!=null){
    		imageView.setImageDrawable(image);}
    	else{
    	   	String msg = "Image can not be loaded!";
        	int duration = Toast.LENGTH_SHORT;
        	Toast toast = Toast.makeText(getApplicationContext(), msg, duration);
        	toast.show();
        	imageView.setImageResource(R.drawable.no_image);
        };
	}
	
	private Dialog showRateDialog(View v) {
		
		LayoutInflater factory = LayoutInflater.from(v.getContext());
        final View dialogView = factory.inflate(R.layout.rate_dialog, null);
        
        return new AlertDialog.Builder(v.getContext())
            .setTitle(R.string.dialog_title)
            .setView(dialogView)
            .setPositiveButton(R.string.rate_button, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	final RatingBar ratingBar = (RatingBar)dialogView.findViewById(R.id.ratingbar2);
                	
                	SharedPreferences pref = getSharedPreferences(LoginView.LOG_KEY_PREFERENCE, Activity.MODE_PRIVATE);
                	String user_key = pref.getString(LoginView.KEY, "");
                	
                	ServiceConnect serviceConnect = ServiceConnect.getInstance(getApplicationContext(), new Handler());
                	serviceConnect.rateSite(user_key, site.getSiteID() , Float.valueOf(ratingBar.getRating()) );
                	}
            })
            .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                	return;
                }
            })
            .show();
	}
	private Dialog showImageDialog(View v){
		return new CustomizeDialog(v.getContext());
	}
	
	/** Class Must extends with Dialog */
	/** Implement onClickListener to dismiss dialog when OK Button is pressed */
	public class CustomizeDialog extends Dialog implements OnClickListener {
		Button okButton;

		public CustomizeDialog(Context context) {
			super(context);
			/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			/** Design the dialog in main.xml file */
			setContentView(R.layout.image_dialog);
			ImageView imageView = (ImageView)findViewById(R.id.imageview);
			imageView.setImageDrawable(image);
//			okButton = (Button) findViewById(R.id.OkButton);
//			okButton.setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
//			/** When OK Button is clicked, dismiss the dialog */
//			if (v == okButton)
//				dismiss();
		}

	}
	
	private int getRatingImageId(float rating){
		if(rating >= 4.8)
			return R.drawable.five;
		if(rating >=4.3  && rating < 4.8)
			return R.drawable.four_half;
		if(rating >=3.8  && rating < 4.3)
			return R.drawable.four;
		if(rating >=3.3  && rating < 3.8)
			return R.drawable.three_half;
		if(rating >=2.8  && rating < 3.3)
			return R.drawable.three;
		if(rating >=2.3  && rating < 2.8)
			return R.drawable.two_half;
		if(rating >=1.8  && rating < 2.3)
			return R.drawable.two;
		if(rating >=1.3  && rating < 1.8)
			return R.drawable.one_half;
		else
			return R.drawable.one;
	}
	
//	public static void setTouchBackround(View v){
//		v.setOnTouchListener(new OnTouchListener() {
//			
//			@Override
//			public boolean onTouch(View v, MotionEvent event) {
//				switch (event.getAction()) {
//				case MotionEvent.ACTION_DOWN:
//					v.setBackgroundResource(R.layout.touch_backround);
//					break;
//				case MotionEvent.ACTION_UP:
//				case MotionEvent.ACTION_OUTSIDE:
//					v.setBackgroundResource(0);
//					break;
//				default:
//					break;
//				}
//				return false;
//			}
//		});
//	}
}